package com.onlinemusic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.onlinemusic.common.R;
import com.onlinemusic.constant.Constants;
import com.onlinemusic.mapper.PayItemMapper;
import com.onlinemusic.mapper.PayMapper;
import com.onlinemusic.mapper.SongMapper;
import com.onlinemusic.pojo.domain.Pay;
import com.onlinemusic.pojo.domain.PayItem;
import com.onlinemusic.pojo.domain.Song;
import com.onlinemusic.pojo.request.SongRequest;
import com.onlinemusic.service.ObjectStoreService;
import com.onlinemusic.service.SongService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialBlob;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class SongServiceImpl extends ServiceImpl<SongMapper, Song> implements SongService {

    @Autowired
    private SongMapper songMapper;

    @Autowired
    private PayMapper payMapper;

    @Autowired
    private PayItemMapper payItemMapper;

    @Autowired
    private ObjectStoreService oss;

    /**
     * 获取所有的歌曲
     *
     * @return
     */
    @Override
    public R allSong() {
        return R.success(null, songMapper.selectList(null));
    }

    /**
     * 增加歌曲
     *
     * @param addSongRequest
     * @param mpfile
     * @return
     */
    @Override
    public R addSong(SongRequest addSongRequest, MultipartFile mpfile) {
        Song song = new Song();
        BeanUtils.copyProperties(addSongRequest, song);
        String pic = "/img/songPic/tubiao.jpg";
        //使用当前时间生成文件名
        String fileName = System.currentTimeMillis() + "-" + mpfile.getOriginalFilename();
        //上传路径
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "song";
        File file = new File(filePath);
        //不存在则创建路径
        if (!file.exists()) {
            if (!file.mkdir()) {
                return R.fatal("创建文件失败");
            }
        }
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        String storeUrlPath = "/song/" + fileName;
        try {
            mpfile.transferTo(dest);
        } catch (IOException e) {
            return R.fatal("上传失败" + e.getMessage());
        }
        //补全数据
        song.setCreateTime(new Date());
        song.setUpdateTime(new Date());
        song.setPic(pic);
        song.setUrl(storeUrlPath);
        if (songMapper.insert(song) > 0) {
            return R.success("上传成功", storeUrlPath);
        } else {
            return R.error("上传失败");
        }
    }

    /**
     * 更新歌曲信息
     *
     * @param updateSongRequest
     * @return
     */
    @Override
    public R updateSongMsg(SongRequest updateSongRequest) {
        Song song = new Song();
        BeanUtils.copyProperties(updateSongRequest, song);
        song.setUpdateTime(new Date());
        if (songMapper.updateById(song) > 0) {
            return R.success("修改成功");
        } else {
            return R.error("修改失败");
        }
    }

    /**
     * 更新歌曲链接也就是内容
     *
     * @param urlFile
     * @param id
     * @return
     */
    @Override
    public R updateSongUrl(MultipartFile urlFile, int id) {
        String fileName = System.currentTimeMillis() + "-" + urlFile.getOriginalFilename();
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "song";
        File file1 = new File(filePath);
        if (!file1.exists()) {
            if (!file1.mkdir()) {
                return R.fatal("创建目的文件夹失败");
            }
        }
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        String storeUrlPath = "/song/" + fileName;
        try {
            urlFile.transferTo(dest);
        } catch (IOException e) {
            return R.fatal("更新失败" + e.getMessage());
        }
//        String urlPath = "song";
//        String ossUrlPath;
//        try{
//            ossUrlPath = oss.uploadFile(urlPath, fileName, urlFile);
//        }catch (IOException e) {
//            throw new RuntimeException(e);
//        }

        Song song = new Song();
        song.setId(id);
        song.setUrl(storeUrlPath);
        song.setUpdateTime(new Date());
        if (songMapper.updateById(song) > 0) {
            return R.success("更新成功", storeUrlPath);
        } else {
            return R.error("更新失败");
        }
    }

    /**
     * 更新歌曲图片
     *
     * @param urlFile
     * @param id
     * @return
     */
    @Override
    public R updateSongPic(MultipartFile urlFile, int id) {
        String fileName = System.currentTimeMillis() + "-" + urlFile.getOriginalFilename();
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "img" + System.getProperty("file.separator") + "songPic";
        File file1 = new File(filePath);
        if (!file1.exists()) {
            if (!file1.mkdir()) {
                return R.fatal("创建文件夹失败");
            }
        }

        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        String storeUrlPath = "/img/songPic/" + fileName;

        try {
            urlFile.transferTo(dest);
        } catch (IOException e) {
            return R.fatal("上传失败" + e.getMessage());
        }

//        String storeUrlPath = "img/songPic";
//        String ossPath;
//        try {
//            ossPath = oss.uploadFile(storeUrlPath, fileName, urlFile);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }

        Song song = new Song();
        song.setId(id);
//        song.setPic(ossPath);
        song.setPic(storeUrlPath);
        song.setUpdateTime(new Date());
        if (songMapper.updateById(song) > 0) {
            return R.success("上传成功", storeUrlPath);
        } else {
            return R.error("上传失败");
        }
    }

    /**
     * 删除歌曲
     *
     * @param id
     * @return
     */
    @Override
    public R deleteSong(Integer id) {
        if (songMapper.deleteById(id) > 0) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

    /**
     * 获取指定歌手的歌曲
     *
     * @param singerId
     * @return
     */
    @Override
    public R songOfSingerId(Integer singerId) {
        QueryWrapper<Song> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("singer_id", singerId);
        return R.success(null, songMapper.selectList(queryWrapper));
    }

    /**
     * 根据songId获取数据 用于展示用户的收藏歌曲
     *
     * @param id
     * @return
     */
    @Override
    public R songOfId(Integer id) {
        QueryWrapper<Song> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        return R.success(null, songMapper.selectList(queryWrapper));
    }

    /**
     * 根据歌手名查询歌曲
     *
     * @param name
     * @return
     */
    @Override
    public R songOfSingerName(String name) {
        QueryWrapper<Song> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);
        return R.success(null, songMapper.selectList(queryWrapper));
    }

    @Override
    public List<Integer> getAllSongIds() {
        return songMapper.selectAllSongIds();
    }

    /**
     * 查询歌单下歌曲
     *
     * @param songListId
     * @return
     */
    @Override
    public R songOfSongListId(int songListId) {
        return R.success("查询成功", songMapper.selectSongListBySongListId(songListId));
    }

    /**
     * 判断是否已经支付
     *
     * @param songId
     * @param userId
     * @return
     */
    @Override
    public R isPay(Integer songId, Integer userId) {
        String msg = "查询歌曲支付状态时发生错误";
        try {
            QueryWrapper<PayItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId).eq("song_id", songId);
            List<PayItem> payItems = payItemMapper.selectList(queryWrapper);
            if (payItems == null) {
                return R.error(msg);
            }
            //歌曲未购买
            if (payItems.isEmpty()) {
                return R.warning("该歌曲还未支付");
            }

            //不等于0时，判断支付清单的状态
            QueryWrapper<Pay> payqw = new QueryWrapper<>();
            payqw.eq("trade_no", payItems.get(0).getTradeNo());
            List<Pay> pays = payMapper.selectList(payqw);

            if (pays == null || pays.size() < 1) {
                return R.error(msg);
            }

            if (pays.get(0).getPayStatus().equals(Constants.PAY_STATUS_1)) {
                return R.success("", true);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return R.error(msg);
        }
        return R.fatal(msg);
    }

    /**
     * 本地链接下载
     *
     * @param url
     * @return
     */
    @Override
    public void downloadSong(String url, HttpServletResponse response) {
        System.out.println(url);
        String basePath = System.getProperty("user.dir");
        String downloadPath = basePath + url;
        try {
            InputStream in = new FileInputStream(downloadPath);
            String fileName = url.substring(url.lastIndexOf("-") + 1);
            System.out.println(fileName);

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            OutputStream out = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("发生错误");
        }
    }

    /**
     * oss下载歌曲
     *
     * @param id
     * @return
     */
    @Override
    public R downloadSong(Integer id) {
        String msg = "歌曲下载时发生错误";
        Song song = songMapper.selectById(id);
        if (song == null) {
            return R.error(msg);
        }

        String userHomeDir = System.getProperty("user.dir");
        String songUrl = song.getUrl();
        String downloadDir = userHomeDir + "/download/song/";
        System.out.println(downloadDir);
        oss.downloadFile(songUrl, downloadDir);

        return R.success("下载成功");
    }

    /**
     * @Description: 获取用户推荐数据
     */
    @Override
    public R getRecommendSongList(Integer userId) {
        return R.success(null, songMapper.selectAllRecommendSongList(userId));
    }
}
